import { useState, useCallback } from "react";
import { View, Text, StyleSheet, ScrollView } from "react-native";

import VideoPlayer from "react-native-media-console";
import Pdf from "react-native-pdf";
import Btn from "@/components/Btn";
import ModalBox from "@/components/ModalBox";
import FullScreenImg from "@/pages/VideoDisplay/FullScreenImg";
import globalMethods from "@/GlobalMethodProvider";

import commonStyles from "@/styles";
import { materialSqlh } from "@/sqlite/exports";
import type { ScheduleSqliteType, MaterialSqliteType } from "@/sqlite/exports";

import styles from "./styles";
import { getPlayFrequencylabel } from "@/config/dictMap";
import useViewList from "@/hooks/useViewList";
import theme from "@/styles/theme";

type Props = {
  /** 当前查看的排期 */
  schedule: ScheduleSqliteType | null;
};

/** 页面状态类型 */
type StateType = {
  /** 排期关联的素材数据 */
  linkMaterial: MaterialSqliteType[];
  /** 视频播放 ModalBox */
  visible: boolean;
  /** 当前选择的素材 */
  selectMaterial: MaterialSqliteType | null;
};

/** 排期信息卡片组件 */
const SchduleInfoCard = ({ schedule }: Props) => {
  const [state, _setState] = useState<StateType>({
    linkMaterial: [],
    visible: false,
    selectMaterial: null
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  /** 统计扫描到的资产信息 */
  const {
    open: openViewList,
    close: closeViewList,
    Comp: CompViewList
  } = useViewList({
    showDel: false,
    modalBoxProps: {
      title: "素材信息",
      width: "80%",
      dismissable: false,
      hideConfirmBtn: true,
      closeBtnText: "关闭"
    },
    ComtentBefore() {
      return (
        <View>
          <Text style={styles.linkMaterialTip}>
            {schedule?.name} 关联素材数据 {state.linkMaterial.length}条, 具体素材信息如下:
          </Text>
        </View>
      );
    },
    getShowItemField() {
      return [
        {
          label: "排序",
          value: (item: MaterialSqliteType) => item.sort
        },
        {
          label: "名称",
          value: (item: MaterialSqliteType) => item.name
        },
        {
          label: "开始时间",
          value: (item: MaterialSqliteType) => item.startTime
        },
        {
          label: "结束时间",
          value: (item: MaterialSqliteType) => item.endTime
        },
        {
          label: "时长",
          value: (item: MaterialSqliteType) => item.duration
        },
        {
          label: "分辨率",
          value: (item: MaterialSqliteType) => item.resolution
        },
        {
          label: "是否下载",
          value: (item: MaterialSqliteType) => {
            return (
              <Text style={{ color: item.isDown === "1" ? theme.danger : theme.primary, fontWeight: "bold" }}>
                {item.isDown === "1" ? "否" : "是"}
              </Text>
            );
          }
        },
        {
          label: "大小",
          value: (item: MaterialSqliteType) => item.size
        }
      ];
    },
    itemClick(item: MaterialSqliteType, i) {
      if (item.isDown === "2") {
        setObjState({ visible: true, selectMaterial: item });
      } else {
        globalMethods.$showMessage({
          type: "toast",
          position: "top",
          message: "该素材还未下载"
        });
      }
    }
  });

  /** 转换为周显示 */
  const playFrequencyFmt = (playWeeks: string) => {
    const dic = {
      "1": "星期一",
      "2": "星期二",
      "3": "星期三",
      "4": "星期四",
      "5": "星期五",
      "6": "星期六",
      "0": "星期日"
    };

    return playWeeks
      .split(",")
      .map(Number)
      .sort((a, b) => a - b)
      .map(e => (dic as any)[e] || "")
      .filter(Boolean)
      .join(" | ");
  };

  /** 查看素材下面的资产 */
  const viewMaterialInfo = async () => {
    if (!schedule) {
      globalMethods.$warning("没有获取到当前排期数据");
      return;
    }

    if (materialSqlh) {
      const res = await materialSqlh.getByCustom<MaterialSqliteType>({
        parentCode: schedule.code
      });
      if (res.length === 0) {
        globalMethods.$warning(`【${schedule.name}】没有关联的素材数据`);
        return;
      }
      const sortData = res.sort((a, b) => a.sort - b.sort);
      setObjState({ linkMaterial: sortData });
      openViewList(sortData);
    } else {
      globalMethods.$error("排期数据库初始化失败");
    }
  };

  /** 内容组件 */
  const ComteneComp = schedule ? (
    <View style={styles.container}>
      <View style={[commonStyles.border, styles.info]}>
        <Text style={styles.text}>排期机构: {schedule.officeName}</Text>
        <Text style={styles.text}>排期创建人员: {schedule.createUserName}</Text>
        <Text style={styles.text}>排期名称: {schedule.name}</Text>
        <Text style={styles.text}>排期编号: {schedule.code}</Text>
        <Text style={styles.text}>
          排期播放日期: {schedule.startDate.split(" ")[0]} ~ {schedule.endDate.split(" ")[0]}
        </Text>
        <Text style={styles.text}>排期开始时间: {schedule.startTime}</Text>
        <Text style={styles.text}>排期播放频次: {getPlayFrequencylabel(schedule.playFrequency)}</Text>
        {schedule.playFrequency === "3" && (
          <Text style={styles.text}>排期播放周次: {playFrequencyFmt(schedule.playWeeks)}</Text>
        )}
        <View style={styles.line}>
          <Text style={styles.text}>排期关联素材:</Text>
          <Btn
            text="查看"
            type="primary"
            btnTextStyle={{ fontSize: 9 }}
            containerStyle={{ height: "90%" }}
            onClick={viewMaterialInfo}
          />
        </View>
      </View>

      {CompViewList}

      <ModalBox
        visible={state.visible}
        dismissable={false}
        title={state.selectMaterial?.name}
        hideConfirmBtn
        onClose={() => setState("visible", false)}
        closeBtnText="关闭"
      >
        <ScrollView style={{ maxHeight: 300, width: "100%" }}>
          <View style={{ height: 300 }}>{state.selectMaterial && getPlayMaterialComp(state.selectMaterial)}</View>
        </ScrollView>
      </ModalBox>
    </View>
  ) : null;

  return ComteneComp;
};

export default SchduleInfoCard;

/** 获取播放的素材对象 */
export function getPlayMaterialComp(selectMaterial: MaterialSqliteType) {
  console.log("selectMaterial: ", selectMaterial);
  const fileProtUri = "file:///" + selectMaterial.downFileToNativePath;
  if (selectMaterial.type === "4") {
    return (
      <VideoPlayer
        // 直接读取本地资源, 不需要加 file:// 前缀
        source={{ uri: selectMaterial.downFileToNativePath }}
        resizeMode="contain"
        isFullscreen // 默认全屏
        showOnStart={false} // 开始时隐藏控件
        showOnEnd={false} // 结束时时隐藏控件
        showDuration // 显示视频时长
        disableBack // 禁用返回按钮
        disableFullscreen // 禁用全屏按钮
        disableVolume // 禁用音量调节
        containerStyle={StyleSheet.absoluteFill} // 容器样式
      />
    );

    // 图片
  } else if (selectMaterial.type === "1") {
    return <FullScreenImg uri={fileProtUri} resizeMode="contain" />;
  } else if (selectMaterial.type === "2") {
    return (
      <Pdf
        style={StyleSheet.absoluteFill}
        source={{ uri: fileProtUri }}
        fitPolicy={0} // 宽度自适应
      />
    );
  } else {
    return (
      <View>
        <Text>素材类型错误请联系管理员</Text>
      </View>
    );
  }
}
